package com.lb.myeam.core.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lb.myeam.common.utils.DBUtil;
import com.lb.myeam.common.utils.StringUtil;
import com.lb.myeam.core.dao.TeamDao;
import com.lb.myeam.core.entity.TeamEntity;

public class TeamDaoImpl implements TeamDao{

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	public boolean add(TeamEntity team) {
		try {
			conn = DBUtil.getConn();
			String sql = "insert into TAB_TEAM values (?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, StringUtil.getUUID());
			pstmt.setString(2, team.getTeamName());
			pstmt.setDate(3,new java.sql.Date(System.currentTimeMillis()));
			pstmt.setString(4, team.getPid());
			int result = pstmt.executeUpdate();
			return result > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(rs, pstmt, conn);
		}
		return false;
	}

	public boolean delete(String id) {
		try {
			conn=DBUtil.getConn();
			String sql="delete from tab_team where id = ?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, id);
			int result=pstmt.executeUpdate();
			return result>0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<TeamEntity> query() {
		List<TeamEntity> teamList = new ArrayList<TeamEntity>();
		try {
			conn = DBUtil.getConn();
			String sql = "select * from TAB_TEAM";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery(sql);
			TeamEntity team;
			while (rs.next()) {
				String id = rs.getString("id");
				String teamName = rs.getString("team_name");
				Date createTime = rs.getDate("create_time");
				String pid = rs.getString("pid");
				team = new TeamEntity(id,teamName,new java.util.Date(createTime.getTime()),pid);
				teamList.add(team);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(rs, pstmt, conn);
		}
		return teamList;
	}

	public boolean update(TeamEntity team) {
		try {
			conn=DBUtil.getConn();
			String sql = "update tab_team set team_name=\'"+team.getTeamName() + 
					"\',create_time="+"sysdate"+
					",pid=\'"+team.getPid()+
					"\' where id=\'"+team.getId()+"\'";
					
			
			pstmt=conn.prepareStatement(sql);
			int result = pstmt.executeUpdate();
			
			return result>0;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(rs, pstmt, conn);
		}
		return false;
	}

}
